package com.ruoyi.common.utils;

import org.opencv.core.*;
import org.opencv.imgcodecs.*;
import org.opencv.imgproc.*;
import org.opencv.photo.Photo;

public class OpenCVImageEnhancer {

    // 加载 OpenCV 库
    static {
        System.load("D:\\Program Files\\opencv\\build\\java\\x64\\opencv_java490.dll");
    }

    public static void enhanceImage(String inputImagePath, String outputImagePath, int width, int height, double sharpness) {
        // 读取原始图片
        Mat image = Imgcodecs.imread(inputImagePath);

        if (image.empty()) {
            System.err.println("Error loading image!");
            return;
        }

        // 1. 提升图像分辨率（超分辨率）
        Mat resizedImage = new Mat();
        Size newSize = new Size(width, height);
        Imgproc.resize(image, resizedImage, newSize, 0, 0, Imgproc.INTER_CUBIC); // 使用更高质量的插值方法

        // 2. 去噪
        Mat denoisedImage = new Mat();

        Photo.fastNlMeansDenoisingColored(resizedImage, denoisedImage, 4, 5, 21);
        // 3. 锐化图像（使用Unsharp Masking）
        Mat blurredImage = new Mat();
        Imgproc.GaussianBlur(denoisedImage, blurredImage, new Size(5, 5), 2.0);

        Mat unsharpMask = new Mat();
        Core.subtract(denoisedImage, blurredImage, unsharpMask);  // 计算锐化掩膜
        Mat sharpenedImage = new Mat();
        Core.add(denoisedImage, unsharpMask, sharpenedImage);  // 进行锐化

        // 可选：多次锐化（避免过度锐化）
//        for (int i = 0; i < 1; i++) {
//            Imgproc.GaussianBlur(sharpenedImage, blurredImage, new Size(5, 5), 1.5);
//            Core.subtract(sharpenedImage, blurredImage, unsharpMask);
//            Core.add(sharpenedImage, unsharpMask, sharpenedImage);
//        }

        // 4. 调整亮度和对比度（避免曝光过度）
        Mat finalImage = new Mat();
        sharpenedImage.convertTo(finalImage, -1, 1.2, -20);  // 1.2 增加对比度，-20 调整亮度

        // 5. 保存输出图像
        Imgcodecs.imwrite(outputImagePath, finalImage);
        System.out.println("Image has been enhanced and saved.");
    }

    public static void main(String[] args) {
        // 输入图片路径
        String inputImage = "E:\\22.jpg";
        // 输出图片路径
        String outputImage = "E:\\output_enhanced.jpg";
        // 提升的目标分辨率 (宽 x 高)
        int width = 512;
        int height = 512;

        // 锐化强度
        double sharpness = 1.8;

        // 调用图像增强方法
        enhanceImage(inputImage, outputImage, width, height, sharpness);
    }
}
